package com.itheima.reggie.common;

import com.fasterxml.jackson.databind.util.Annotations;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.lang.annotation.Annotation;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author :XingJiaCheng
 * @date :2022-04-19-15:04
 * @description
 **/
@Slf4j
@ResponseBody
@ControllerAdvice(annotations = {Controller.class, RestController.class})
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String>exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());
        if (ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            return R.error("输入的" + split[2] + "用户名重复");
        }
        return R.error("未知错误");

    }
    @ExceptionHandler(SQLException.class)
    public  R<String>exceptionHandler(SQLException ex){
        log.error(ex.getMessage());
        return R.error("错误:" + ex.getMessage());
    }
    @ExceptionHandler(CustomException.class)
    public R<String>CustomException(CustomException ex){
        log.error(ex.getMessage());
        return R.error(ex.getMessage());
    }
}
